import re
from flask import g,redirect,request,jsonify,current_app,session

# 导入蓝图
from info import db,constants
from info.modules.profile import profile_blue
# 导入装饰器
from info.utils.comments import login_required
# 导入模型类
from info.models import User,House
# 导入7牛云
from info.utils.image_storage import storage
# 导入自定义错误类型
from info.utils.response_code import RET

# 获取用户信息
@profile_blue.route('/user',methods=['GET'])
@login_required
def fnUser():
    # 获取用户信息
    user = g.user
    if not user:
        return redirect('/')
    # 获取参数
    name = user.name
    mobile = user.mobile
    avatar_url = user.avatar_url
    data = {
        "avatar_url":constants.QINIU_DOMIN_PREFIX + avatar_url if avatar_url else None,
        "name":name,
        'mobile':mobile
    }
    return jsonify(errno=RET.OK, errmsg='OK',data=data)

# 用户名修改
@profile_blue.route('/user/name',methods=['POST'])
@login_required
def user_name():
    # 获取用户信息
    user = g.user
    if not user:
        return redirect('/')
    # 获取参数
    name = request.json.get('name')
    # 检查参数
    if not name:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    # 保存用户信息
    user.name = name
    # 提交数据
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DATAERR, errmsg='提交数据失败')
    return jsonify(errno=RET.OK, errmsg='OK')

# 上传个人头像
@profile_blue.route('/user/avatar',methods=['POST'])
@login_required
def user_avatar():
    user = g.user
    # 获取参数
    avater_url = request.files.get('avatar')
    if not avater_url:
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')
    # 读取图片
    try:
        image_data = avater_url.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg='读取数据错误')
    # 把读取后的图片数据传入七牛云
    try:
        image_name = storage(image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg='上传图片异常')
    # 保存图片内容到mysql
    user.avatar_url = image_name
    # 提交数据
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg='保存数据失败')
    # 拼接图片的绝对路径，返回前端
    avatar_url = constants.QINIU_DOMIN_PREFIX + image_name
    # 返回图片
    data = {
        'avatar_url':avatar_url
    }
    return jsonify(errno=RET.OK,errmsg="OK",data=data)



# 获取用户实名信息
@profile_blue.route('/user/auth',methods=['GET'])
@login_required
def user_authA():
    user = g.user
    # 检查用户是否登录
    if not user:
        return redirect('/')
    # 从数据库中获取参数
    real_name = user.real_name
    id_card = user.id_card

    # 返回前端
    data = {
        'real_name':real_name,
        'id_card':id_card
    }
    return jsonify(errno=RET.OK,errmsg='OK',data=data)

# 设置用户实名信息
@profile_blue.route('/user/auth',methods=['POST'])
@login_required
def user_authB():
    user = g.user
    # 获取用户信息
    real_name = request.json.get('real_name')
    id_card = request.json.get('id_card')
    # 检查参数的完整
    if not all([real_name,id_card]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数缺失')
    # 检查身份证的正则
    if not re.match(r'^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$',id_card):
        return jsonify(errno=RET.DATAERR,errmsg='请输入正确的身份号')
    # 保存用户信息
    user.real_name = real_name
    user.id_card = id_card
    # 提交数据
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg='保存数据失败')
    return jsonify(errno=RET.OK, errmsg='OK')


# 我的房屋发布列表
@profile_blue.route('/user/houses')
@login_required
def user_houses():
    user = g.user
    # 获取房屋信息
    if not user:
        return jsonify(errno=RET.SESSIONERR,errmsg='用户未登录')

    try:
        user_houses = House.query.filter(House.user_id==user.id).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询房屋发布信息失败')
    # 判断查询数据是否为空
    if not user_houses:
        return jsonify(errno=RET.NODATA,errmsg='无房屋发布信息')
    # 遍历查询到的数据并添加到列表
    user_houses_list = []
    for user_house in user_houses:
        user_houses_list.append(user_house.to_basic_dict())
    # 返回数据给前端
    return jsonify(errno=RET.OK,errmsg='ok',data = user_houses_list)